package com.mashibing.class04;

/**
 * @Auther: huangxiaode
 * @Date: 2024-01-31 - 01 - 31 - 16:58
 * @Description: com.mashibing.class04
 * @version: 1.0
 */
// 测试链接：https://leetcode.com/problems/merge-two-sorted-lists
public class Code06_MergeTwoSortedLinkedList {
    // 不要提交这个类
    public static class ListNode {
        public int val;
        public ListNode next;
    }

    public static ListNode mergeTwoLists(ListNode head1, ListNode head2) {
        if (head1 == null || head2 == null) { // 两个链表中 有一个链表为空 直接返回, 不需要合并.
            return head1 == null ? head2 : head1;
        }
        ListNode head = head1.val <= head2.val ? head1 : head2;
        ListNode cur1 = head.next; // 小链表头的下一个为cur1
        ListNode cur2 = head == head1 ? head2 : head1; // 大链表头作为cur2
        ListNode pre = head; // pre 用来 连接新链表的.
        while (cur1 != null && cur2 != null) {
            if (cur1.val <= cur2.val) {
                pre.next = cur1;
                cur1 = cur1.next;
            } else {
                pre.next = cur2;
                cur2 = cur2.next;
            }
            pre = pre.next;
        }
        // 到最后了, cur1和cur2 谁不为空, pre的next就指向谁.
        pre.next = cur1 != null ? cur1 : cur2;
        return head;
    }
}
